package com.zf.shuashua.ui.game;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.duoyou.task.openapi.DyAdApi;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.tencent.bugly.beta.Beta;
import com.zf.shuashua.MainActivity;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.InteractionAdListener;
import com.zf.shuashua.advert.NativeAdvertManager;
import com.zf.shuashua.advert.OnRewardListener;
import com.zf.shuashua.advert.RewardAdvertManager;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BaseFragment;
import com.zf.shuashua.bean.GameJson;
import com.zf.shuashua.bean.Giftjson;
import com.zf.shuashua.bean.JumpJson;
import com.zf.shuashua.bean.NationalBean;
import com.zf.shuashua.bean.ToShare;
import com.zf.shuashua.manager.CalendarManager;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.ui.popup.OnPopupListener;
import com.zf.shuashua.ui.popup.RewardPopupFragment;
import com.zf.shuashua.utils.CommonConstants;
import com.zf.shuashua.utils.Util;
import com.zf.shuashua.utils.WebUtils;

import org.greenrobot.eventbus.EventBus;

import static com.umeng.socialize.utils.ContextUtil.getPackageName;

public class GameWelfareFragment extends BaseFragment{

    public static final int REFRESH = 5;//刷新
    public static final int WITHDRAW = 8;//提现
    private WebView webview;
    private String url = Constants.H5_URL + "my_game";

    private String mAdvertType = AdvertConstants.REWARD_TYPE_TASK;

    public static GameWelfareFragment newInstance() {
        Bundle args = new Bundle();
        GameWelfareFragment fragment = new GameWelfareFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView(View root) {
        webview = root.findViewById(R.id.webview);
        initWebView();
        webview.loadUrl(url);
    }

    @Override
    public void initViewModel() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_game_welfare;
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings ws = webview.getSettings();
        // 网页内容的宽度是否可大于WebView控件的宽度
        ws.setLoadWithOverviewMode(false);
        // 保存表单数据
        ws.setSaveFormData(true);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        ws.setSupportZoom(true);
        ws.setBuiltInZoomControls(true);
        ws.setDisplayZoomControls(false);
        // 启动应用缓存
        ws.setAppCacheEnabled(true);
        // 设置缓存模式
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
        ws.setUseWideViewPort(true);
        // 不缩放
//        webView.setInitialScale(100);
        // 告诉WebView启用JavaScript执行。默认的是false。
        ws.setJavaScriptEnabled(true);
        //  页面加载好以后，再放开图片
        ws.setBlockNetworkImage(false);
        // 使用localStorage则必须打开
        ws.setDomStorageEnabled(true);
        // 排版适应屏幕
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // WebView是否新窗口打开(加了后可能打不开网页)
//        ws.setSupportMultipleWindows(true);

        // webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        /** 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用)*/
        ws.setTextZoom(100);

//        mWebChromeClient = new MyWebChromeClient(this);
//        webview.setWebChromeClient(mWebChromeClient);
        // 与js交互
        webview.addJavascriptInterface(new TaskJSInterface(), "android");
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    }


    //============================== App to H5 ==============================

    //"type": String, // "PUNCH":会员签到, "TASK" :限次激励, "SHARE_VIDEO"：分享任务,
    // "FIRST_GET" :首次观看,  "LIKE" :点赞视频, "BIND_WECHAT"：绑定微信, "OPEN_NOTIFICATION"：开启推送, "TIME_LIMIT"：限时登录, "APPRAISE"：长豆评价
    //result: true 成功 false：失败
    private void rewardedAdvertResult(String result) {
        quickCallJs("rewardedAdvertResult", null, mAdvertType, result);
    }

    private void popViewCallbackEvent(String popType) {
        quickCallJs("PopViewCallbackEvent", null, popType);
    }


    private void quickCallJs(String method, ValueCallback<String> callback, String... params) {
        StringBuilder sb = new StringBuilder();
        sb.append("javascript:" + method);
        if (params == null || params.length == 0) {
            sb.append("()");
        } else {
            sb.append("(").append(WebUtils.concat(params)).append(")");
        }
        callJs(sb.toString(), callback);
    }

    private void callJs(String js, final ValueCallback<String> callback) {
        if (webview != null) {
            webview.evaluateJavascript(js, null);
        }
    }

    //============================== App to H5 ==============================

    public void reload() {
        if (webview != null) {
//            webview.reload();
            quickCallJs("refreshData", null);
        }
    }

    private boolean ToLogin() {
        if (!Store.getInstance().isLogin()) {
            Intent intent = new Intent(mActivity, LoginActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    //获取当前版本号
    private String getVersionName() {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = mActivity.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            String version = packInfo.versionName;
            return version;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0";
    }

    private void jumpToFriend() {
        if (!ToLogin()) {
            startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "helpEarn").putExtra("title", "邀请好友").putExtra("Refresh", true), REFRESH);
        }
    }

    private void dealWithdrawResult(String value, int flag, String comeFrom) {
        if (TextUtils.isEmpty(value)) {
            return;
        }
        if ("activity_cash".equals(comeFrom)) {
            return;
        }
        if (flag == 4 || flag == 5) {
            if (flag == 4) {
                jumpToFriend();
            } else if (flag == 5) {
                ((MainActivity) mActivity).openHome();
            }
            return;
        }
        if ("0.3".equals(value)) {

        } else if ("5".equals(value)) {
            jumpToFriend();
        } else if ("3".equals(value)) {

        } else if ("10".equals(value)) {
            ((MainActivity) mActivity).openHome();
        } else if ("50".equals(value)) {
            ((MainActivity) mActivity).openHome();
        } else if ("100".equals(value)) {
            ((MainActivity) mActivity).openHome();
        }
    }

    private RewardPopupFragment mPopupFragment;

    public boolean isShowPopup() {
        if (mPopupFragment == null) {
            return false;
        }
        return mPopupFragment.isVisible();
    }

    private void hidePopupFragment() {
        if (mPopupFragment == null) return;
        hideFragment(mPopupFragment);
        mPopupFragment = null;
    }

    private class TaskJSInterface {

        @JavascriptInterface
        public String getToken() {
            return ShuaApplication.token;
        }

        @JavascriptInterface
        public String getDeviceId() {
            return Util.getDeviceId(ShuaApplication.getContext());
        }

        @JavascriptInterface
        public String getBlackBox() {
            return ShuaApplication.blackbox;
        }

        @JavascriptInterface
        public String getAccessToken() {
            return ShuaApplication.accessToken;
        }

        @JavascriptInterface
        public String getChannel() {
            return ShuaApplication.channel;
        }

        @JavascriptInterface
        public void openHome() {
            if (getContext() instanceof MainActivity) {
                MainActivity mainActivity = (MainActivity) getContext();
                mainActivity.openHome();
            }
        }

        @JavascriptInterface
        public void openHot() {
            if (getContext() instanceof MainActivity) {
                MainActivity mainActivity = (MainActivity) getContext();
                mainActivity.openHot();
            }
        }

        @JavascriptInterface
        public void openGame() {
            if (!ToLogin()) {
                /**
                 * userId : 用户uid
                 * advertType: 0（默认值）显示全部数据  1.手游  2.棋牌游戏
                 */
                DyAdApi.getDyAdApi().jumpAdList(mActivity, Store.getInstance().getuserId(), 0);
            }
        }

        //进入单个游戏 json: {"advertId" : "1111"}
        @JavascriptInterface
        public void jumpAdDetail(String json) {
            if (TextUtils.isEmpty(json)) {
                return;
            }
            GameJson result = ParseJsonUtils.parseData(json + "", GameJson.class);
            if (result == null || TextUtils.isEmpty(result.getAdvertId())) {
                return;
            }
            DyAdApi.getDyAdApi().jumpAdDetail(mActivity, Store.getInstance().getuserId(), result.getAdvertId());
        }

        //分享至第三方平台
        @JavascriptInterface
        public void share() {
            if (getContext() instanceof MainActivity) {
                MainActivity mainActivity = (MainActivity) getContext();
                mainActivity.openHome();
                EventBus.getDefault().post(new ToShare());
            }
        }

        private boolean isRewarding = false;

        //激励视频
        //"type": String, // "PUNCH":会员签到, "TASK" :限次激励, "SHARE_VIDEO"：分享任务,
        // "FIRST_GET" :首次观看,  "LIKE" :点赞视频, "BIND_WECHAT"：绑定微信, "OPEN_NOTIFICATION"：开启推送, "TIME_LIMIT"：限时登录, "APPRAISE"：长豆评价
        @JavascriptInterface
        public void rewardedAdvert(String type) {
            callRewardedAdvert(type, "");
        }

        @JavascriptInterface
        public void rewardedAdvertEvent(String type, String reportId) {
            callRewardedAdvert(type, reportId);
        }

        private void callRewardedAdvert(String type, String reportId){
            mActivity.runOnUiThread(() -> {
                if (isRewarding) {
                    return;
                }
                isRewarding = true;
                if (webview != null) {
                    webview.postDelayed(() -> isRewarding = false, 2000);
                } else {
                    isRewarding = false;
                }
                if (!ToLogin()) {
                    mAdvertType = type;
                    RewardAdvertManager.getInstance().showAdvert(mActivity, mAdvertType, reportId, new OnRewardListener() {
                        @Override
                        public void onAdClose() {
                            rewardedAdvertResult("true");
                        }

                        @Override
                        public void onAdClick() {

                        }

                        @Override
                        public void onVideoComplete() {

                        }

                        @Override
                        public void onVideoError() {
                            rewardedAdvertResult("false");
                        }
                    });
                }
            });
        }

        //to提现
        @JavascriptInterface
        public void toWallet() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "withdraw").putExtra("title", "我的钱包"), WITHDRAW);
                //任务：945109760； 签到：945109757
//            loadAd("945109757", "任务", rewardAmount);

            }
        }

        //跳转到h5的次级界面
        @JavascriptInterface
        public void redirectEvent(String uri, String title) {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + uri).putExtra("title", title), CommonConstants.MAIN);
            }
        }

        //to兑换/金豆
        @JavascriptInterface
        public void toWing() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "wallet?tabs=1").putExtra("title", "我的金豆"), CommonConstants.MAIN);
            }
        }

        //to邀请好友/师徒
        @JavascriptInterface
        public void toFriend() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "helpEarn").putExtra("title", "邀请好友").putExtra("Refresh", true), REFRESH);
            }

        }

        //to补填邀请码
        @JavascriptInterface
        public void toCode() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "invite").putExtra("title", "补填邀请码").putExtra("Refresh", true), REFRESH);
            }

        }

        //to身份信息完善
        @JavascriptInterface
        public void toPersonal() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "setInfo").putExtra("title", "完善信息").putExtra("Refresh", true), REFRESH);
            }
        }

        //是否不再提醒
        @JavascriptInterface
        public boolean isCalendarReminded() {
            return CalendarManager.getInstance().isCalendarReminded();
        }

        @JavascriptInterface
        public void setCalendarReminded() {
            CalendarManager.getInstance().setCalendarReminded(true);
        }

        // 开启提醒规则
        @JavascriptInterface
        public void startCalendarRemind() {
            CalendarManager.getInstance().startCalendarRemind(getActivity());
        }

        @JavascriptInterface
        public String getAppVersion() {
            return getVersionName();
        }

        @JavascriptInterface
        public String getSystemModel() {
            return android.os.Build.MODEL;
        }

        @JavascriptInterface
        public String getApiVersion() {
            return CommitUtils.API_VERSION;
        }

        /**
         * 跳转到指定界面
         *
         * @param data json格式，{"type": "home"}
         *             "home":视频首页；"task":任务；"friend":邀请好友；"xdraw":提现；"hot_share";热点视频分享；
         */
        @JavascriptInterface
        public void jumpEvent(String data) {
            mActivity.runOnUiThread(() -> {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JumpJson result = ParseJsonUtils.parseData(data + "", JumpJson.class);
                if (result == null) {
                    return;
                }
                EventBus.getDefault().post(result);
            });
        }


        @JavascriptInterface
        public void login() {
            Intent intent = new Intent(mActivity, LoginActivity.class);
            startActivity(intent);
        }

        private boolean isPopShowing;

        //关闭回调：PopNationDayCallbackEvent，传jsonString
        //type: startNow：“立即开始”；dayReward：1号到7号的奖励弹窗；giftReward：8号的礼品奖励
        @JavascriptInterface
        public void PopNationDayEvent(String jsonString) {
            mActivity.runOnUiThread(() -> {
                NationalBean result = ParseJsonUtils.parseData(jsonString + "", NationalBean.class);
                //TODO: 1、show pop; 2、call PopNationDayCallbackEvent after pop close

            });
        }

        //检查更新
        @JavascriptInterface
        public void checkUpgrade() {
            mActivity.runOnUiThread(Beta::checkUpgrade);
        }

        @JavascriptInterface
        public void PopViewEvent(String jsonString) {
            mActivity.runOnUiThread(() -> {
                if (isPopShowing) {
                    return;
                }
                isPopShowing = true;
                if (webview != null) {
                    webview.postDelayed(() -> isPopShowing = false, 1500);
                } else {
                    isPopShowing = false;
                }
                hidePopupFragment();
                Giftjson result = ParseJsonUtils.parseData(jsonString + "", Giftjson.class);
                mPopupFragment = RewardPopupFragment.newInstance(result.getTitle(), result.getSubTitle(), result.getValue(), result.getUiType() + "", result.getPopType());
                mPopupFragment.setPopupListener(new OnPopupListener() {
                    @Override
                    public void onNext() {
                        hidePopupFragment();
                        popViewCallbackEvent(result.getPopType());
                    }

                    @Override
                    public void onClose() {
                        hidePopupFragment();
                    }
                });
                showFragment(R.id.fl_popup, mPopupFragment);
                NativeAdvertManager.getInstance().loadExpressAd(mActivity, AdvertConstants.NATIVE_TYPE_ENCOURAGE, new InteractionAdListener() {
                    @Override
                    public void onRenderSuccess(View view) {
                        webview.postDelayed(() -> {
                            if (mPopupFragment != null) {
                                mPopupFragment.addAdvertView(view);
                            }
                        }, 400);
                    }

                    @Override
                    public void onError() {
                        webview.postDelayed(() -> {
                            if (mPopupFragment != null) {
                                mPopupFragment.loadAdvertFail();
                            }
                        }, 400);
                    }
                });
            });
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        if (webview != null && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return super.onBackPressedSupport();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.destroy();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommonConstants.MAIN) {
            if (resultCode == RESULT_OK) {
                ((MainActivity) mActivity).openHome();
            }
        } else if (requestCode == WITHDRAW) {
            if (resultCode == RESULT_OK) {
                try {
                    String value = data.getStringExtra("value");
                    String comeFrom = data.getStringExtra("comeFrom");
                    int flag = data.getIntExtra("flag", 0);
                    dealWithdrawResult(value, flag, comeFrom);
                } catch (Exception e) {
                    ((MainActivity) mActivity).openHome();
                }
            }
        } else if (requestCode == REFRESH) {
            if (resultCode == RESULT_OK) {
                reload();
            }
        }
    }

}
